<template>
  <!-- 该年度指标列表用于中交和中咨共用,参数type会有所区别 -->
  <div class="container">
    <div class="annual-index-title">{{ routeQuery.name }}指标库</div>
    <el-row class="" style="margin-bottom: 20px">
      <el-col :span="16" align="left">
        <el-input
          v-model="searchFrom.param"
          placeholder="指标名称/编号"
          style="width: 150px; margin-right: 15px"
          @change="search"
          clearable
        />
        <el-button class="ordinary" @click="search()">搜索</el-button>
      </el-col>
      <el-col :span="8" align="right" v-if="state.annualDetail">
        <el-button class="ordinary" @click="getExportBtn()">批量导出</el-button>
        <span
          v-if="state.annualDetail.status == '1' || state.annualDetail.lockFlag == '0'"
          style="margin-left: 10px"
        >
          <el-button type="danger" @click="handleDetect()">删除</el-button>
          <el-button class="lock" @click="handleCopy()">复制</el-button>
          <el-button type="primary" @click="handleAdd()">新增指标</el-button>
        </span>
      </el-col>
    </el-row>
    <div>
      <el-table
        :data="state.table_list"
        style="width: 100%"
        v-loading="state.table_loading"
        row-key="id"
        border
        ref="qwltTable"
        @selection-change="selectionChange"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column
          type="selection"
          width="55"
          lign="center"
          :reserve-selection="false"
          fixed="left"
        />
        <el-table-column prop="number" width="200" label="指标编号"  align="left"  fixed="left"  />
        <el-table-column prop="name" label="指标名称" align="center"  width="160"   fixed="left"  />
        <el-table-column
          prop="indexType_text"
          align="center"
          label="指标类型"
          width="120"
        />
        <el-table-column prop="scoreType_text" align="center" label="计分类型" width="100">
        </el-table-column>
        <el-table-column
          prop="scoreMethod_text"
          align="center"
          label="评分方式"
          width="100"
        >
        </el-table-column>
        <el-table-column prop="score" align="center" label="指标分数(H)" width="160" />
        <el-table-column
          prop="superFinalScore"
          align="center"
          label="最终得分"
          v-if="standardType === '1'"
          width="120"
        />
        <el-table-column
          prop="scoreCompose"
          align="center"
          label="系统计分组成"
          width="240"
        >
          <template #default="scope">
            {{ filterScoreCompose(scope.row.scoreCompose, scope.row.scoreSource) }}
          </template>
        </el-table-column>
        <el-table-column prop="indexIntro" align="center" label="指标说明"  width="300"  />
        <el-table-column prop="createUsername" align="center" label="创建人" width="100" />
        <el-table-column prop="createTime" align="center" label="创建时间"  width="150"  />
        <el-table-column prop="modifyUsername" align="center" label="自评人" width="100" />
        <el-table-column prop="modifyTime" align="center" label="自评时间"  width="150" />

        <el-table-column prop="superIndexAnnualExamine" align="center" label="关联中交年度指标" width="150" >
          <template #default="scope">
            {{ filtersuperIndexAnnualExamine(scope.row.superIndexAnnualExamine) }}
          </template>
        </el-table-column>
        <el-table-column prop="superIndexAnnualBank" align="center" label="关联投入产出类指标" width="150">
          <template #default="scope" >
            {{ filtersuperIndexAnnualBank(scope.row.superIndexAnnualBank) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="address"
          fixed="right"
          align="center"
          label="操作"
          width="260"
        >
          <template #default="scope">
            <!-- status字段是中交指标列表中才有的所以可以理解为用status判断的就是只存在于中交指标，反之lockFlag就是只属于中咨的 -->
            <span v-if="state.annualDetail.lockFlag == '1'">
              <!-- //草稿状态 -->
              <el-button type="ordinary" @click="handleLook(scope.row)">查看</el-button>

                <el-button
                  type="primary"
                  @click="giveScoreManage(scope.row, 'look')"
                  v-if="scope.row.scoreMethod === '1'"
                  >查看评分设置</el-button
                >
            </span>
            <span
              v-if="
                state.annualDetail.status == '1' || state.annualDetail.lockFlag == '0'
              "
            >
              <!-- //草稿状态 -->
              <el-button class="ordinary" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button
                type="primary"
                v-if="scope.row.scoreMethod === '1'"
                @click="giveScoreManage(scope.row, 'edit')"
                >评分管理</el-button
              >
            </span>
            <span v-if="state.annualDetail.status == '2'">
              <!-- 考核中 -->
              <el-button
                type="primary"
                class="operationBtn"
                v-if="scope.row.scoreMethod === '2'||(scope.row.scoreCompose&&scope.row.scoreCompose.includes('A1000'))"
                @click="openSelf(scope.row, 'selfM')"
                >自评管理</el-button
              >
              <el-button
                type="primary"
                v-if="scope.row.scoreMethod === '1' || scope.row.scoreSource == '01'"
                class="operationBtn"
                @click="goScoreDetail(scope.row)"
                >系统打分明细</el-button
              >
              <el-button
                type="primary"
                v-if="scope.row.scoreSource == '01'"
                class="operationBtn"
                @click="openSelf(scope.row, 'quality')"
                >质量自评</el-button
              >
            </span>
            <span v-if="state.annualDetail.status == '3'">
              <!-- 考核结束 -->
              <el-button
                type="primary"
                v-if="scope.row.scoreMethod === '2'||(scope.row.scoreCompose&&scope.row.scoreCompose.includes('A1000'))"
                class="operationBtn"
                @click="openSelf(scope.row, 'selfM', 'look')"
                >查看自评</el-button
              >
              <el-button
                type="primary"
                class="operationBtn"
                v-if="scope.row.scoreMethod === '1' || scope.row.scoreSource == '01'"
                @click="goScoreDetail(scope.row)"
                >查看明细</el-button
              >
              <el-button
                type="primary"
                class="operationBtn"
                v-if="scope.row.scoreSource == '01'"
                @click="openSelf(scope.row, 'quality', 'look')"
                >查看质量自评</el-button
              >
            </span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <editAddStandardIndex
      v-model:visible="state.modalVisible"
      @refresh="gettargetlist"
      :opType="state.opType"
      :dictDatas="dictDatas"
      :standardType="standardType"
      :editForm="state.handleRowData"
      :assignParams="assignParams"
      :insertApi="state.insertApi"
      :updateApi="state.updateApi"
      :parentNumOption="state.table_list"
      :isRelated="standardType == '2'"
    ></editAddStandardIndex>
    <scoreManModal
      v-model:visible="state.scoreManVisible"
      :handleRow="state.handleRowData"
      :apiPackage="apiPackage"
      :pageDisabled="state.scoreManDisabled"
    ></scoreManModal>
    <el-dialog
      v-model="selfAssParams.selfassVisible"
      :title="selfAssParams.title"
      width="500px"
    >
      <div style="padding-top: 10px">
        <el-form
          :model="selfAssForm"
          ref="selfAssRef"
          :rules="selfRules"
          label-width="120px"
        >
          <el-form-item label="指标名称:">
            {{ selfAssParams.indexName }}
          </el-form-item>
          <el-form-item label="手动评分:" prop="selfScore"><!--需要可以输入两位小数 -->
<!--            <el-input-number-->
            <el-input
              :disabled="selfAssParams.selfAssType == 'look'"
              v-model="selfAssForm.selfScore"
              style="width: 200px"
              :controls="false"
              :max="99"
              :min="0"
              maxlength="5"
              oninput="value=value.replace(/[^\d.]/g, '') .replace(/\.{2,}/g, '.') .replace(/^(\-)*(\d+)\.(\d{2}).*$/, '$1$2.$3') .replace(/^\./g, '') .replace(/^0+(\d+)/, '$1') .replace(/^(\d{2})\d+$/, '$1')"

            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="selfAssParams.selfassVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="confirmSelf"
            v-if="selfAssParams.selfAssType !== 'look'"
          >
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, nextTick } from "vue";
// import Table from '../../../components/indexTable.vue'
import * as api from "../../api/examineManage";
import { ElMessageBox, ElMessage } from "element-plus";
import editAddStandardIndex from "../zjExamine/standardIndexLibrary/addAndEdit.vue";
import scoreManModal from "../zjExamine/standardIndexLibrary/scoreManModal.vue";
import { useRoute, useRouter } from "vue-router";
import { dataDictionary } from "@/api/dict";
import pubFc from "../../utils";
interface Cdata {
  [propName: string]: any;
}
const searchFrom = reactive({
  //查询
  param: "",
});
// const refreshPage:any=inject('refreshPage', Function, true);
let standardType = ref("1"); //该参数决定显示的是中交还是中咨的年度指标列表
const route = useRoute();
const router = useRouter();
const routeQuery = route.query;
const selfAssRef = ref<any>();
standardType.value = route.path=='/examineManage/techExamine/zjExamine/annualILb'?'1':'2';
const assignParams = reactive({
  annualId: routeQuery.aid,
});
const apiPackage = reactive({
  //中交的评分管理接口包
  detail: standardType.value == "1" ? "ZjAannualSetRequest" : "zzannDetailRequest",
  score: standardType.value == "1" ? "zjAnSetSRequest" : "updateZzScoreRuleRequest",
  insert: standardType.value == "1" ? "insertZjAnSetequest" : "insertZzSetRequest",
  update: standardType.value == "1" ? "updateZjAnSetequest" : "updateZzSetRequest",
  delete: standardType.value == "1" ? "deleteZjAnSetequest" : "deleteZzSetRequest",
});
const selfRules = reactive({
  selfScore: [{ required: true, message: "请填写评分", trigger: "blur" }],
});
let state = reactive<Cdata>({
  table_list: [],
  modalVisible: false,
  opType: "add", //add,edit,copy
  handleRowData: null, //正在处理的行数据
  scoreManVisible: false,
  annualDetail: null,
  table_loading: false,
  insertApi:
    standardType.value == "1" ? "insertZjAannualRequest" : "insertZzindexRequest",
  updateApi: standardType.value == "1" ? "editZjAannualRequest" : "updateZzindexRequest",
  scoreManDisabled: false, //评分管理页面是否可以操作false就是可以
});
const dictDatas = reactive({
  dict_indexTypes: [],
  dict_indexNames: [],
  dict_scoreTypes: [],
  dict_scoreMethods: [],
  dict_scoreSources_zj: [],
  dict_scoreSources_zz: [],
  dict_scoreCompose_zj: [],
  dict_scoreCompose_zz: [],
}); //字典值
const selfAssForm = reactive({
  selfScore: undefined,
});
let selectedRows = ref<any>([]);
const search = () => {
  //搜索
  gettargetlist();
};
const filterScoreCompose = (scoreCompose, scoreSource) => {
  let str = "",
    dict_list = [];
  dict_list =
    standardType.value === "1"
      ? dictDatas.dict_scoreSources_zj
      : dictDatas.dict_scoreSources_zz;
  let cd: any = dict_list.find((it: any) => it.itemValue === scoreSource);
  dict_list = cd ? cd.children : [];
  if (scoreCompose && dict_list.length) {
    scoreCompose.map((item) => {
      let t = dict_list.find((item2) => (item2 as any).itemValue === item);
      if (t) {
        str += "+" + (t as any).itemText;
      }
    });
    str = str.substring(1);
  }
  return str;
};
const filtersuperIndexAnnualExamine = (superIndexAnnualExamine) => {
  let str = "";
  if (superIndexAnnualExamine != null) {
    str = superIndexAnnualExamine.name
  }
  return str;
};
const filtersuperIndexAnnualBank = (superIndexAnnualBank) => {
  let str = "";
  // if (superIndexAnnualBanktwo.includes('superIndexAnnualBank')){
    if (superIndexAnnualBank != null) {
      str = superIndexAnnualBank.name
    }
  // }



  return str;
};
const getExportBtn = () => {
  //批量导出

  let apiName =
    standardType.value == "1" ? "exportzjIndexRequest" : "exportzzIndexRequest";
  api[apiName]({
    annualId: routeQuery.aid,
    ...searchFrom,
  }).then((res) => {
    const { data, headers } = res;
    pubFc.downloadFunc(data, headers);
  });
};
const selectionChange = (arr) => {
  //选中
  selectedRows.value = arr;
};
const handleDetect = () => {
  //批量删除

  if (selectedRows.value.length === 0) {
    ElMessage({
      message: "请选择数据后删除！",
      type: "warning",
    });
  } else if (selectedRows.value.length > 1) {
    ElMessage({
      message: "请选择一条数据！",
      type: "warning",
    });
  } else {
    ElMessageBox.confirm("确定要删除选中数据吗?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      // let sel_ids=selectedRows.value.map(item=>{return item.id});deleteAnnZzRequest
      let apiName =
        standardType.value == "1" ? "deleteAnnZjRequest" : "deleteAnnZzRequest";
      api[apiName]({
        id: selectedRows.value[0].id,
      }).then((res) => {
        if (res.data.code == 200) ElMessage.success("删除成功");
        gettargetlist();
      });
    });
  }
};

const handleAdd = () => {
  //新增
  state.opType = "add";
  state.modalVisible = true;
};
const handleEdit = (item) => {
  //编辑
  state.opType = "edit";
  state.handleRowData = item;
  state.modalVisible = true;
};
const handleLook = (item) => {
  state.opType = "look";
  state.handleRowData = item;
  state.modalVisible = true;
};
const handleCopy = () => {
  if (selectedRows.value.length !== 1) {
    ElMessage({
      message: "请选择一条数据复制",
      type: "warning",
    });
  } else {
    state.opType = "copy";
    state.handleRowData = selectedRows.value[0];
    state.modalVisible = true;
  }
};
const giveScoreManage = (item, type) => {
  //评分管理
  state.scoreManDisabled = type == "look" ? true : false;
  state.handleRowData = item;
  state.scoreManVisible = true;
};
const goScoreDetail = (row) => {
  console.log('row',row);

  //跳转到得分明细
  router.push({
    path: "/examineManage/techExamine/zjExamine/scoreDetail",
    query: {
      id: row.id,
      name: row.name,
      aid: routeQuery.aid,
    },
  });
};
const selfAssParams = reactive({
  //自评管理或质量自评弹窗的参数
  selfAssType: "save", //save/look
  selfassVisible: false,
  title: "",
  indexName: "", //指标名
  saveApi: "",
});

const openSelf = (row, selfType, type = "save") => {
  //打开质量自评或自评管理
  selfAssParams.selfassVisible = true;
  nextTick(() => {
    selfAssRef?.value.resetFields();
    selfAssParams.selfAssType = type; //弹窗形式，保存还是查看
    selfAssParams.indexName = row.name;
    state.handleRowData = row;
    // selfAssForm.selfScore=row.superAnnualExamineIndexScore?row.superAnnualExamineIndexScore.selfScore:undefined
    selfAssForm.selfScore = undefined;
    // if (type == "look") {
      let apiName =
        selfType == "selfM" ? "checkSelfEvaluateRequest" : "checkQualityEvaluateRequest";
      api[apiName]({
        id: row.id,
      }).then((res) => {
        selfAssForm.selfScore = res.data.data.selfScore || undefined;
      });
    // }else{
    //   selfAssForm.selfScore = row.superAnnualExamineIndexScore?row.superAnnualExamineIndexScore.selfScore:undefined;
    // }
    if (selfType === "selfM") {
      //自评管理
      selfAssParams.title = type == "save" ? "自评管理" : "查看自评";
      selfAssParams.saveApi = "saveSelfEvaluateRequest";
    } else {
      selfAssParams.title = type == "save" ? "质量自评" : "查看质量自评";
      selfAssParams.saveApi = "saveQualityEvaluateRequest";
    }
  });
};

const confirmSelf = () => {
  //保存自评管理
  selfAssRef?.value.validate((valid) => {
    if (valid) {
      api[selfAssParams.saveApi]({
        id: state.handleRowData.id,
        selfScore: selfAssForm.selfScore,
      }).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("保存成功");
          selfAssParams.selfassVisible = false;
          gettargetlist();
        }
      });
    }
  });
};
const getDictDatas = () => {
  return new Promise((resolve, reject) => {
    state.table_loading = true;
    let dictIds = [
      "KHGL_CLASS_INDEX_NAME_CODE",
      "KHGL_INDEX_TYPE_CODE",
      "KHGL_SCORE_METHOD_CODE",
      "KHGL_SCORE_TYPE_CODE",
      "KHGL_ZJ_EXAMINE_SCORE_METHOD_CODE",
      "KHGL_ZZ_EXAMINE_SCORE_METHOD_CODE",
    ];
    dataDictionary(dictIds).then((res) => {
      let response = res.data.data;
      dictDatas.dict_indexTypes = response.KHGL_INDEX_TYPE_CODE;
      dictDatas.dict_indexNames = response.KHGL_CLASS_INDEX_NAME_CODE;
      dictDatas.dict_scoreTypes = response.KHGL_SCORE_TYPE_CODE;
      dictDatas.dict_scoreMethods = response.KHGL_SCORE_METHOD_CODE;
      dictDatas.dict_scoreSources_zj = response.KHGL_ZJ_EXAMINE_SCORE_METHOD_CODE;
      dictDatas.dict_scoreSources_zz = response.KHGL_ZZ_EXAMINE_SCORE_METHOD_CODE;
      if (standardType.value === "1") {
        //中交
        response.KHGL_ZJ_EXAMINE_SCORE_METHOD_CODE.map((item) => {
          dictDatas.dict_scoreCompose_zj = dictDatas.dict_scoreCompose_zj.concat(
            item.children
          );
        });
      } else {
        response.KHGL_ZZ_EXAMINE_SCORE_METHOD_CODE.map((item) => {
          dictDatas.dict_scoreCompose_zz = dictDatas.dict_scoreCompose_zz.concat(
            item.children
          );
        });
      }

      resolve(1);
    });
  });
};
const getDetail = () => {
  //先查询详情再根据详情中的状态来判断页面
  return new Promise((resolve, reject) => {
    let apiName =
      standardType.value == "1" ? "annualDetailRequest" : "zzAnnualDetailRequest";
    api[apiName]({
      id: routeQuery.aid,
    }).then((res) => {
      state.annualDetail = res.data.data;
      resolve(1);
    });
  });
};
// let table_list=reactive<any>([]);
  const qwltTable=ref<any>();
const gettargetlist = () => {
  //获取标准指标库列表
  state.table_loading = true;
  let apiName =
    standardType.value == "1" ? "zjIndexlistRequest" : "getZzindexListRequest";
  console.log("standardType.value", standardType.value);
  api[apiName]({
    ...searchFrom,
    annualId: routeQuery.aid, //1-中交标准指标、2-中咨标准指标
  }).then((res) => {
    state.table_loading = false;
    state.table_list = res.data.data;
    nextTick(()=>{
        if(qwltTable.value){  //使用了父子级后选中第一级再查询后这一级就无法清除了
          (qwltTable as any).value.clearSelection();
        }

      })
  });
};

getDictDatas().then(() => {
  getDetail().then(() => {
    gettargetlist();
  });
});
</script>
<style lang="scss" scoped>
.container {
  background-color: white;
  padding: 20px;
  overflow-y: auto;
  .annual-index-title {
    text-align: center;
    padding-bottom: 10px;
    border-bottom: 1px solid #e7e5e5;
    margin-bottom: 10px;
    font-size: 26px;
  }
}
:deep(.el-dialog__header) {
  border-bottom: 1px solid #ccc;
}
// :deep(.el-dialog__body) {
//   padding: 0 !important
// }
:deep(.el-dialog__body) {
  padding: 0;
}

.dialogCloseBtn {
  position: absolute;
  top: 20px;
  right: 20px;
}

// .el-col {
//   line-height: 60px;
// }

.pageName {
  font-weight: 700;
}
.operationBtn{
  margin: 5px;
}
</style>
